#include "gui_info.h"
//
/*  Save file as gui_info.cpp  */
/*  incomming class name Gui_Info */
//
#include <QCloseEvent>

Gui_Info::Gui_Info( NetworkDav * db , QString path , const QString mirrordir )
{
	setupUi( this );
    locMirror = mirrordir;
    ///////////qDebug() << "#### constructor   ############" << path << "  " << mirrordir;
    path = path;
    lastopgoing = -1;
    workonlevel = -1;
    passaggiwake = 0;
    startpath = path;
    dbdav = db;
    remotepath = RealRemotePath(path);
    label->setText(remotepath);
    label_2->setText("");
    aborter = false;
    if (!path.endsWith("/")) {
    close();
    } else {
    Load_Connector();
    }
}

void Gui_Info::Load_Connector()
{
    Get_File.clear();
    Workin_Dir.clear();
    Unique_Dir.clear();
    aborter = false;
    ButtonSetup();
    lastopgoing = -1;
    connect(dastop, SIGNAL(clicked()), this, SLOT(StopCicles()));   
    connect(dago, SIGNAL(clicked()), this, SLOT(StartCicles())); 
    Unique_Dir.append("/");  
    Unique_Dir.append(startpath);    
    InfoPath(startpath,0);
}

/* get structure recursive */
void Gui_Info::InfoPath( QString const dir , int level )
{
    if (!aborter) {
        workonlevel = level;
        lastopgoing = -1;
        if ( !Unique_Dir.contains(dir) ) {
             ////////////Unique_Dir.append(dir);  
        } else {
                 if (Workin_Dir.size() > 0) {
                /////// qDebug() << "#############PRENDONUOVO#######" << Workin_Dir.at(0) <<  "#################################################### ";
                 Workin_Dir.removeFirst();   
                 }             
        }
        
        /////////////////qDebug() << "#### GET INFO from start  dir->############" << dir << "   level->" << level;
        
        label->setText(tr("Get info from: %1").arg(RealRemotePath(dir)));
        label_2->setText("");
            DavPROPFIND *listin = new DavPROPFIND(dbdav,dir);
                  listin->SetFormat(INFODIRLISTFORMAT,level);
     connect(listin, SIGNAL(WarningMsg(QString)), this, SLOT(ShowMessageWarning(QString)));
     connect(listin, SIGNAL(InfoDavList(QStringList,QStringList,int)), this, SLOT(RegisterRecursive(QStringList,QStringList,int)));
    } else {
    StopCicles();
    }
}

 void Gui_Info::GrabNextlevel( int level )
{
    workonlevel = level;
    NextInfoDir(0,level);
}


 void Gui_Info::NextInfoDir( int now , int level  )
{
    
    if (aborter) { 
        return;
    }
    
    int bigmap = Workin_Dir.size();
    if (bigmap < 0) {
    Workin_Dir.clear();
    RegisterRecursive(Workin_Dir,Workin_Dir,level + 1);
    return;
    }
    
    if (now >= bigmap) { 
    Workin_Dir.clear();
    RegisterRecursive(Workin_Dir,Workin_Dir,level + 1);
    return;
    }
      for (int i = 0; i < Workin_Dir.size(); ++i)  {
                      if (now == i) {
                         const QString anextpath =  Workin_Dir.at(i);
                          if (anextpath.size() > 0) {
                           InfoPath(anextpath,level);
                          } else {
                            NextInfoDir(now + 1 ,level); 
                              
                          }
                      return;
                      }
     }
     
     /////////Workin_Dir.clear();
     
}




void  Gui_Info::RegisterRecursive(QStringList xdir ,QStringList xfile , int level )
{
   
    //////////qDebug() << "#### inlevel->" << level;
    //////////////qDebug() << "#### inxdir->" << xdir;
    
    int newdir = 0;
    
    
    for (int i = 0; i < xdir.size(); ++i)  {
                  if ( xdir.at(i) !=startpath and xdir.at(i) != dbdav->DummiRoot()  ) {
                      if (!Unique_Dir.contains(xdir.at(i)) ) {
                       Unique_Dir.append(xdir.at(i));  
                       Workin_Dir.append(xdir.at(i));
                       newdir++;
                      }
                      
                  }        
     }
     
    
    for (int i = 0; i < xfile.size(); ++i)  {
                      if (!Get_File.contains(xfile.at(i))) {
                         //////////qDebug() << "#### append file " << xfile.at(i);
                          Get_File.append(xfile.at(i));  
                      }
                         
     }
     

     
     ////////qDebug() << "#### Unique_Dir.size()  ->" << Unique_Dir.size();
     ////////////////qDebug() << "#### Workin_Dir.size()  ->" << Workin_Dir.size();
     //////////////qDebug() << "#### Get_File.size()  ->" << Get_File.size();
     
     
     
     
     if (newdir > 0  or Workin_Dir.size() > 0 ) {
        GrabNextlevel( level + 1 );
        return;
     }
     
     
     if (Get_File.size() > 0) {
         ////////////Get_Dir.clear();
      /* download fake file ........*/
         WakeUpsFile();
     }


     
}


 void Gui_Info::WakeUpsFile()
{
    passaggiwake++;
   ///////////qDebug() << "#### star downlaod ->" << passaggiwake;
      if ( passaggiwake >= 2) {
       return;
      } 
    Workin_Dir.clear();
    Unique_Dir.clear();
    QStringList RFile = ReverseList(Get_File);
    Get_File.clear();
    Get_File = RFile;
    NextFileGet(0);
      return;
    
       for (int i = 0; i < Get_File.size(); ++i) {
           ///////////qDebug() << "### download file exec   -> " << Get_File.at(i);
            const QString remotef = RealRemotePath( Get_File.at(i) );
            const QString flocal = ToLocalPathPath( Get_File.at(i) );
            //////////////qDebug() << "### remotef   -> " << remotef;
           //////////////qDebug() << "### flocal   -> " << flocal;
           
       }
      
      
    
    
}





 void Gui_Info::NextFileGet( int now )
{
    lastopgoing = now;
    if (aborter) { 
        return;
    }
    
    int bigmap = Get_File.size();
    
    if (now >= bigmap) { 
    Get_File.clear();
    label_2->setText("");
    lastopgoing = -1;
    close();
    ///////////////qDebug() << "### endddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd  ";
    return;
    }
      for (int i = 0; i < Get_File.size(); ++i)  {
                      if (now == i) {
                         const QString remotef = RealRemotePath( Get_File.at(i) );
                                       actualurl = remotef;
                         const QString flocal = ToLocalPathPath( Get_File.at(i) );
                          label_2->setText(tr("Download pos. %2 file %1").arg(remotef).arg(i));
                          label->setText(tr("Recursive Download Path: %1").arg(RealRemotePath(startpath)));
                          BeamLogFile = new QFile(flocal); 
                          
    davinfo = new QHttp();
    davinfo->setHost(dbdav->Host(),dbdav->Port());
    davinfo->setUser(dbdav->User(),dbdav->Pass());
    QHttpRequestHeader header("GET", remotef,1,1);   /* header */
    header.setValue("Host", dbdav->Host());
    header.setValue("User-Agent", WEBAGENTNAME );
    header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    header.setValue("Accept-Language", "it,de-de;q=0.8,it-it;q=0.6,en-us;q=0.4,en;q=0.2");
    header.setValue("Connection", "keep-alive");
    david = davinfo->request(header,0,BeamLogFile);                 
    connect(davinfo, SIGNAL(dataReadProgress(int, int)), this, SLOT(SendStatus(int, int)));
    connect(davinfo, SIGNAL(requestFinished(int, bool)), this, SLOT(Wake_Finish(int, bool))); 
                      return;
                      }
     }
     
}


 
void Gui_Info::ShowMessageWarning( QString msg )
{
    StopCicles();
    QMessageBox::warning(this, tr("Error from Gui Download Dav_Module!"),msg);
    
}
//


void Gui_Info::StopCicles()
{
    aborter = true;
    ////////////qDebug() << "### stop  ";
    ButtonSetup();
    if (lastopgoing > 0 or lastopgoing == 0) {
        if (david > 0 ) {
            davinfo->abort();
        }
    }
}


void Gui_Info::StartCicles()
{
    aborter = false;
    ButtonSetup();
    
    if (lastopgoing > 0 or lastopgoing == 0) {
        
        if ( !davinfo->hasPendingRequests() ) {
            int avio = davinfo->currentId();
            if (avio == david) {
                david = davinfo->get(actualurl,BeamLogFile);
                return; 
            } else {
             NextFileGet(lastopgoing);
            }
        } else {
        NextFileGet(lastopgoing);
        }
        return;
    } else {
       passaggiwake = 0;
       Load_Connector(); 
    }
}



void Gui_Info::ButtonSetup()
{
	if (!aborter)  {
     dastop->setEnabled(true);
     dago->setEnabled(false);
    } else {
     dastop->setEnabled(false);
     dago->setEnabled(true);
        
    }
}




QString Gui_Info::RealRemotePath( QString dirorfile )
{
    QString remotefilefolder = QString("%1%2").arg(dbdav->DummiRoot()).arg(dirorfile);
    return remotefilefolder.replace("//","/");
}

QString Gui_Info::ToLocalPathPath( QString remotefile )
{
    QString difile = QString("%1%2").arg(locMirror).arg(remotefile);
    difile = difile.replace("//","/");
    fwriteutf8(difile,"1");
    qt_unlink(difile);
    return difile;
}





void Gui_Info::closeEvent( QCloseEvent* e )
{
    if ( davinfo->hasPendingRequests() ) {
        BeamLogFile->close();
        davinfo->close();
    }
	e->accept();
    delete this;
}





void  Gui_Info::SendStatus( int bytesRead, int totalBytes )
{

   running->setMaximum(totalBytes);
   running->setValue(bytesRead);
    
}




void  Gui_Info::Wake_Finish( int requestId, bool error )
{
   if (requestId != david ) {
     return;
   }
   david = -1;
    QHttpResponseHeader lastheader = davinfo->lastResponse();
    int statuscode = lastheader.statusCode();
    BeamLogFile->close();
    davinfo->close();
   
    if (error) {
    ShowMessageWarning(tr("Error on url: \nErrorMsg %1\nheader code %2").arg(davinfo->errorString()).arg(statuscode));
    return;
    } 
    
    if (lastopgoing == 0 or lastopgoing > 0) {
        NextFileGet(lastopgoing + 1);
        return;
    }
    
    close();
    
}









